<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    用户名：<input id="username" />
    <script>
      //防抖函数，对函数fn的调用防抖，delay是延迟时间
      function debounce(fn, delay) {
        timer = null;
        return function () {
          //上下文
          let ctx = this;
          //参数
          let args = arguments;
          if (timer) {
            //清空时钟，重新计时
            clearTimeout(timer);
          }
          //延迟delay指定的时间后执行函数
          timer = setTimeout(function () {
            fn.apply(ctx, args);
          }, delay);
        };
      }

      document.getElementById("username").addEventListener(
        "keyup",
        debounce((event) => {
          console.log(
            "用户" + ["不存在", "存在"][new Date().getUTCMilliseconds() % 2]
          );
        }, 2000),
        false
      );
    </script>
  </body>
</html>
